package com.cblz.bd.server.core.filter;

import com.cblz.bd.server.core.handle.ResetRequestWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * {@code @Name:} CachingRequestBodyFilter
 * {@code @Description: } 缓存请求Body，防止调用后 getReader() has already been called for this request
 * {@code @Author:} by yanjieping
 * {@code @CreateDate:} 2022/12/8 - 周四
 */
@Component
public class CachingRequestBodyFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String method = httpServletRequest.getMethod();
        if (StringUtils.equals(method, "DELETE")) {
            ResetRequestWrapper resetRequestWrapper = new ResetRequestWrapper(httpServletRequest);
            chain.doFilter(resetRequestWrapper, servletResponse);
        } else {
            chain.doFilter(servletRequest, servletResponse);
        }
    }

}
